//
//  M1MessageListVC.m
//  NewMarryU
//
//  Created by apple on 2018/7/11.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1MessageListVC.h"
#import "M1MsgHeader.h"
#import "M1MessageViewController.h"
#import "M1HomeModel.h"
@interface M1MessageListVC ()<EaseConversationListViewControllerDelegate, EaseConversationListViewControllerDataSource>
@property (nonatomic ,strong) M1MsgHeader *m1_messageHead;
@end

@implementation M1MessageListVC
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:m1_boldFont(16),NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self refresh];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self m1_creatUI];
    
}
-(void)m1_creatUI{
    self.navigationItem.title = @"消息";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = m1_bg_color;
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;
    self.tableView.backgroundColor = m1_bg_color;
    self.tableView.separatorColor = m1_line_color;
  
    [self tableViewDidTriggerHeaderRefresh];
    [self removeEmptyConversationsFromDB];
    UIImageView *m1_naView = [[UIImageView alloc]init];
    m1_naView.image = [UIImage imageNamed:@"msg_bg"];
    m1_naView.contentMode = UIViewContentModeScaleAspectFill;
    m1_naView.clipsToBounds = YES;
    m1_naView.userInteractionEnabled = YES;
    [self.view addSubview:m1_naView];
    [m1_naView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(0);
        make.right.offset(0);
        make.height.mas_offset(m1_NAV_HEIGHT+15);
    }];

    UIView *m1_bgView = [[UIView alloc]init];
    m1_bgView.backgroundColor = m1_bg_color;
    [self.view addSubview:m1_bgView];
    m1_bgView.frame = CGRectMake(0, m1_NAV_HEIGHT, SCREENWIDTH, SCREENHEIGHT-m1_NAV_HEIGHT-(iPhoneX?83:49));
    [m1_bgView m1_roundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight radii:CGSizeMake(15, 15)];
    [m1_bgView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}

- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.type == EMConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            [needRemoveConversations addObject:conversation];
        }
    }
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EMClient sharedClient].chatManager deleteConversations:needRemoveConversations isDeleteMessages:YES completion:nil];
    }
}
#pragma mark - EaseConversationListViewControllerDelegate
- (void)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
            didSelectConversationModel:(id<IConversationModel>)conversationModel
{
    if (conversationModel) {
        EMConversation *conversation = conversationModel.conversation;
        if (conversation) {
           
            M1MessageViewController *m1_messageVC = nil;
            m1_messageVC = [[M1MessageViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:EMConversationTypeChat];
            NSDictionary *dic = [[EaseDataBase sharedDataBase] queryWeixinWithSessionId:conversation.conversationId];
            m1_messageVC.m1_uid = dic[@"uid"];
            m1_messageVC.hidesBottomBarWhenPushed = YES;
            m1_messageVC.title = conversationModel.title;
            if ([conversationModel.conversation.conversationId isEqualToString:[@"100000" m1_MD5]]||[conversationModel.conversation.conversationId isEqualToString:[@"100001" m1_MD5]]||[conversationModel.conversation.conversationId isEqualToString:[@"100002" m1_MD5]]||[conversationModel.conversation.conversationId isEqualToString:[@"100003" m1_MD5]]) {
                m1_messageVC.m1_isSysTem = YES;
                
            }
            [self.navigationController pushViewController:m1_messageVC animated:YES];
        }
       
        [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
        [self.tableView reloadData];
    }
}

#pragma mark - EaseConversationListViewControllerDataSource
-(void)clickAvtar:(id<IConversationModel>) model{
    if ([model.conversation.conversationId isEqualToString:[@"100000" m1_MD5]]||[model.conversation.conversationId isEqualToString:[@"100001" m1_MD5]]||[model.conversation.conversationId isEqualToString:[@"100002" m1_MD5]]||[model.conversation.conversationId isEqualToString:[@"100003" m1_MD5]]||[model.conversation.conversationId isEqualToString:[@"200000" m1_MD5]]) {
        return;
    }
    NSDictionary *dic = [[EaseDataBase sharedDataBase] queryWeixinWithSessionId:model.conversation.conversationId];
    M1HomeModel *m1_homeModel = [M1HomeModel new];
    M1HomeBasic *m1_basic = [M1HomeBasic new];
    m1_basic.uid = [dic m1_stringKey:@"uid"];
    m1_homeModel.basic = m1_basic;
    M1HomeDetailsVC *m1_detailVC = [[M1HomeDetailsVC alloc]init];
    m1_detailVC.m1_hiddenNav = YES;
    m1_detailVC.m1_model = m1_homeModel;
    m1_detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:m1_detailVC animated:YES];
}
- (id<IConversationModel>)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                                    modelForConversation:(EMConversation *)conversation
{
    EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];
    if (model.conversation.type == EMConversationTypeChat) {
    } else if (model.conversation.type == EMConversationTypeGroupChat) {
        NSString *imageName = @"groupPublicHeader";
        if (![conversation.ext objectForKey:@"subject"])
        {
            NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.conversationId]) {
                    NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
                    [ext setObject:group.subject forKey:@"subject"];
                    [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
                    conversation.ext = ext;
                    break;
                }
            }
        }
        NSDictionary *ext = conversation.ext;
        model.title = [ext objectForKey:@"subject"];
        imageName = [[ext objectForKey:@"isPublic"] boolValue] ? @"groupPublicHeader" : @"groupPrivateHeader";
        model.avatarImage = [UIImage imageNamed:imageName];
    }
    return model;
}
- (NSAttributedString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@""];
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    if (lastMessage) {
        NSString *latestMessageTitle = @"";
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
                if ([lastMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                    latestMessageTitle = @"[动画表情]";
                }
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
        NSDictionary *ext = conversationModel.conversation.ext;
        if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtAllMessage) {
            latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atAll", nil), latestMessageTitle];
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
            [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atAll", nil).length)];
        }
        else if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtYouMessage) {
            latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atMe", @"[Somebody @ me]"), latestMessageTitle];
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
            [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atMe", @"[Somebody @ me]").length)];
        }
        else {
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
        }
    }
    if ([[conversationModel.conversation.latestMessage.ext m1_stringKey:@"hx_attr_exchange_wx"] boolValue]) {
        if ([conversationModel.conversation.latestMessage.from isEqualToString:[[M1User user].basic.uid m1_MD5]]) {
            attributedStr = [[NSMutableAttributedString alloc] initWithString:@"请求交换微信已发送"];
        }else{
            attributedStr = [[NSMutableAttributedString alloc] initWithString:@"我想和你交换微信，您是否同意？"];
        }
    }
    if ([[conversationModel.conversation.latestMessage.ext m1_stringKey:@"hx_attr_refuse_exchange_wx_account"] boolValue]) {
        if ([conversationModel.conversation.latestMessage.from isEqualToString:[[M1User user].basic.uid m1_MD5]]) {
            attributedStr = [[NSMutableAttributedString alloc] initWithString:@"您拒绝了对方的微信交换请求"];
        }else{
            attributedStr = [[NSMutableAttributedString alloc] initWithString:@"对方拒绝了您的微信交换请求"];
        }
    }
    
    if ([[conversationModel.conversation.latestMessage.ext m1_stringKey:@"hx_attr_show_wx_account"] boolValue]) {
        if ([conversationModel.conversation.latestMessage.from isEqualToString:[[M1User user].basic.uid m1_MD5]]) {
            NSString *m1_name = conversationModel.title;
            if (m1_name.length >6) {
                m1_name = [NSString stringWithFormat:@"%@...",[m1_name substringWithRange:NSMakeRange(0, 6)]];
            }
            NSString *string = [NSString stringWithFormat:@"%@的微信号: %@",m1_name,[conversationModel.conversation.latestMessage.ext m1_stringKey:@"hx_attr_show_other_wx_account"]];
            attributedStr = [[NSMutableAttributedString alloc] initWithString:string];
        }else{
            NSString *m1_name = [conversationModel.conversation.latestMessage.ext m1_stringKey:@"nick_name"];
            if (m1_name.length >6) {
                m1_name = [NSString stringWithFormat:@"%@...",[m1_name substringWithRange:NSMakeRange(0, 6)]];
            }
            NSString *string = [NSString stringWithFormat:@"%@的微信号: %@",m1_name,[conversationModel.conversation.latestMessage.ext m1_stringKey:@"hx_attr_show_my_wx_account"]];
            attributedStr = [[NSMutableAttributedString alloc] initWithString:string];
        }
    }
    return attributedStr;
}
- (NSString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
       latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        latestMessageTime = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
    }
    return latestMessageTime;
}
#pragma mark - public
-(void)tableViewDidTriggerHeaderRefresh{
    [super tableViewDidTriggerHeaderRefresh];
    [self refresh];
}
-(void)refresh
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSArray* sorted = [conversations sortedArrayUsingComparator:
                       ^(EMConversation *obj1, EMConversation* obj2){
                           EMMessage *message1 = [obj1 latestMessage];
                           EMMessage *message2 = [obj2 latestMessage];
                           if(message1.timestamp > message2.timestamp) {
                               return(NSComparisonResult)NSOrderedAscending;
                           }else {
                               return(NSComparisonResult)NSOrderedDescending;
                           }
                       }];
    [self.dataArray removeAllObjects];
    for (EMConversation *converstion in sorted) {
        EaseConversationModel *model = nil;
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(conversationListViewController:modelForConversation:)]) {
            model = [self.dataSource conversationListViewController:self
                                               modelForConversation:converstion];
        }
        else{
            model = [[EaseConversationModel alloc] initWithConversation:converstion];
        }
        if (model) {
            NSDictionary *dic = [[EaseDataBase sharedDataBase] queryWeixinWithSessionId:model.conversation.conversationId];
            model.title = dic[@"name"];
            model.avatarURLPath = dic[@"avatar"];
            [self.dataArray addObject:model];
        }
    }
    [self refreshAndSortView];
    [self prepareData];
    [[M1TabBarController instance] m1_updateUnReadMessage];
}
-(void)refreshDataSource
{
    [self tableViewDidTriggerHeaderRefresh];
    [self prepareData];
}
-(void)prepareData{
    EaseConversationModel *m1_HN;

    for (int i = 0; i<self.dataArray.count; i++) {
        EaseConversationModel *model = self.dataArray[i];
        if ([model.conversation.conversationId isEqualToString:[@"100000" m1_MD5]]) {
            m1_HN = model;
            break;
        }
    }
    
    if (!m1_HN) {
        self.tableView.tableHeaderView = self.m1_messageHead;
    }else{
        self.tableView.tableHeaderView = [UIView new];
        m1_HN.avatarImage = [UIImage imageNamed:@"ms_kefu"];
        m1_HN.title = @"小红娘";
        [self.dataArray removeObject:m1_HN];
        [self.dataArray insertObject:m1_HN atIndex:0];
    }

    [self.tableView reloadData];
}
- (M1MsgHeader *)m1_messageHead{
    if (!_m1_messageHead) {
        _m1_messageHead = [[M1MsgHeader alloc]init];
        _m1_messageHead.backgroundColor = [UIColor whiteColor];
        _m1_messageHead.frame = CGRectMake(0, 0, SCREENWIDTH, 60);
        [_m1_messageHead.clickBtn  addTarget:self action:@selector(clivkBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m1_messageHead;
}
-(void)clivkBtn{
    M1MessageViewController *m1_messageVC = [[M1MessageViewController alloc]initWithConversationChatter:[@"100000" m1_MD5] conversationType:EMConversationTypeChat];
    m1_messageVC.hidesBottomBarWhenPushed = YES;
    m1_messageVC.m1_uid = @"100000";
    m1_messageVC.navigationItem.title = @"小红娘";
    m1_messageVC.m1_isSysTem = YES;
    [self.navigationController pushViewController:m1_messageVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
